//
//  WBNetworkManager+Extension.swift
//  新浪微博
//
//  Created by zj on 2017/10/15.
//  Copyright © 2017年 zj. All rights reserved.
//

import Foundation

extension WBNetworkManager {
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list: [[String: AnyObject]]?, _ isSuccess: Bool)->()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
//        let params = ["access_token": "2.00zHmosD1TOCdB94df90b521cG8Z3B"]

        let params = ["since_id": "\(since_id)",
            "max_id": "\(max_id > 0 ? max_id - 1 : 0)"]
        
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
//            print(json)
            let result = json?["statuses"] as? [[String: AnyObject]]
            completion(result, isSuccess)
        }
    }
    
    func unreadCount(completion: @escaping (_ count: Int) -> ()) {
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let params = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            let dict = json as? [String: AnyObject]
            let count = dict?["status"] as? Int
            
            completion(count ?? 0)
        }
    }
}

extension WBNetworkManager {
    func loadUserInfo(completion: @escaping (_ dict: [String: AnyObject])->()) {
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            completion(json as? [String : AnyObject] ?? [:])
        }
    }
}

extension WBNetworkManager {
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": WBAppKey,
            "client_secret": WBAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WBRedirectURI]
        
        request(method: .POST, URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            self.userAccount.yy_modelSet(with: json as? [AnyHashable : Any] ?? [:])
            
            self.userAccount.access_token = "2.00zHmosD1TOCdB822e0beeb5_BdLND"
            
            self.loadUserInfo(completion: { (dict) in                
                self.userAccount.yy_modelSet(with: dict)
                
                self.userAccount.saveAccount()

                print(self.userAccount)
                
                completion(isSuccess)
            })
        }
    }
}
